<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统 - 图书管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            height: 100vh;
            overflow: hidden;
        }

        .sidebar {
            height: 100%;
            background-color: #2c3e50;
            color: white;
            padding-top: 20px;
            position: fixed;
            z-index: 1;
        }

        .sidebar a {
            color: white;
            text-decoration: none;
            display: block;
            padding: 12px 20px;
            margin-bottom: 5px;
            border-radius: 4px;
            transition: background-color 0.3s;
        }

        .sidebar a:hover {
            background-color: #34495e;
            color: white;
        }

        .sidebar a.active {
            background-color: #1abc9c;
        }

        .content {
            margin-left: 250px;
            padding: 20px;
            height: 100vh;
            overflow-y: auto;
            background-color: #f8f9fa;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e9ecef;
        }

        .search-bar {
            background-color: white;
            padding: 15px;
            border-radius: 6px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .table-container {
            background-color: white;
            border-radius: 6px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1050;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background-color: white;
            padding: 25px;
            border-radius: 6px;
            width: 100%;
            max-width: 650px;
            max-height: 90vh;
            overflow-y: auto;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e9ecef;
        }

        .logout-btn {
            cursor: pointer;
        }

        .btn-action {
            margin: 0 3px;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 50px;
        }

        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .fade-in {
            animation: fadeIn 0.5s;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                height: auto;
                position: relative;
            }
            .content {
                margin-left: 0;
            }
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <!-- 侧边栏 -->
        <div class="col-md-3 col-lg-2 d-md-block sidebar collapse">
            <h3 class="text-center mb-4">图书馆管理系统</h3>
            <a href="/books.html" class="active"><i class="bi bi-book"></i> 图书管理</a>
            <a href="/staff.html"><i class="bi bi-people"></i> 员工管理</a>
            <a href="/users.html"><i class="bi bi-person"></i> 用户管理</a>
            <div class="mt-5">
                <a href="#" id="logoutLink" class="logout-btn"><i class="bi bi-box-arrow-right"></i> 退出登录</a>
            </div>
        </div>

        <!-- 主内容区 -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 content">
            <div class="header">
                <h2>图书管理</h2>
                <div id="userInfo" class="text-right"></div>
            </div>

            <!-- 搜索区域 -->
            <div class="search-bar">
                <div class="row g-3">
                    <div class="col-md-3">
                        <input type="text" class="form-control" id="searchTitle" placeholder="书名">
                    </div>
                    <div class="col-md-3">
                        <input type="text" class="form-control" id="searchAuthor" placeholder="作者">
                    </div>
                    <div class="col-md-3">
                        <input type="text" class="form-control" id="searchIsbn" placeholder="ISBN">
                    </div>
                    <div class="col-md-3">
                        <button class="btn btn-primary" id="searchBtn"><i class="bi bi-search"></i> 搜索</button>
                        <button class="btn btn-secondary" id="resetBtn"><i class="bi bi-arrow-clockwise"></i> 重置</button>
                        <button class="btn btn-success" id="addBookBtn"><i class="bi bi-plus-circle"></i> 添加图书</button>
                    </div>
                </div>
            </div>

            <!-- 加载中提示 -->
            <div class="loading" id="loading">
                <div class="spinner-border text-primary" role="status">
                    <span class="sr-only">加载中...</span>
                </div>
                <p class="mt-2">正在加载数据，请稍候...</p>
            </div>

            <!-- 图书表格 -->
            <div class="table-container fade-in">
                <table class="table table-striped table-hover">
                    <thead class="thead-dark">
                    <tr>
                        <th>ID</th>
                        <th>ISBN</th>
                        <th>书名</th>
                        <th>作者</th>
                        <th>出版社</th>
                        <th>出版年份</th>
                        <th>分类</th>
                        <th>总数量</th>
                        <th>可借数量</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="booksTableBody">
                    <!-- 图书数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
        </main>
    </div>
</div>

<!-- 添加/编辑图书模态框 -->
<div class="modal" id="bookModal">
    <div class="modal-content fade-in">
        <div class="modal-header">
            <h4 id="modalTitle">添加新图书</h4>
            <button type="button" class="close" id="closeModal">&times;</button>
        </div>
        <form id="bookForm">
            <input type="hidden" id="bookId">
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="isbn" class="form-label">ISBN <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="isbn" required>
                </div>
                <div class="form-group col-md-6">
                    <label for="title" class="form-label">书名 <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="title" required>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="author" class="form-label">作者 <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="author" required>
                </div>
                <div class="form-group col-md-6">
                    <label for="publisher" class="form-label">出版社</label>
                    <input type="text" class="form-control" id="publisher">
                </div>
            </div>

            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="publicationYear" class="form-label">出版年份</label>
                    <input type="number" class="form-control" id="publicationYear" min="1000" max="2100">
                </div>
                <div class="form-group col-md-6">
                    <label for="category" class="form-label">分类</label>
                    <input type="text" class="form-control" id="category">
                </div>
            </div>

            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="quantity" class="form-label">总数量 <span class="text-danger">*</span></label>
                    <input type="number" class="form-control" id="quantity" min="0" required>
                </div>
                <div class="form-group col-md-6">
                    <label for="availableQuantity" class="form-label">可借数量 <span class="text-danger">*</span></label>
                    <input type="number" class="form-control" id="availableQuantity" min="0" required>
                </div>
            </div>

            <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> 保存</button>
            <button type="button" class="btn btn-secondary" id="cancelBtn"><i class="bi bi-x-circle"></i> 取消</button>
        </form>
    </div>
</div>

<!-- 提示消息模态框 -->
<div class="modal" id="messageModal">
    <div class="modal-content" style="max-width: 400px;">
        <div class="modal-header">
            <h5 id="messageTitle" class="modal-title">提示</h5>
            <button type="button" class="close" id="closeMessageModal">&times;</button>
        </div>
        <div class="modal-body">
            <p id="messageContent"></p>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-primary" id="confirmMessageBtn">确定</button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 页面加载时检查登录状态
    $(document).ready(function() {
        const token = localStorage.getItem('token');
        if (!token) {
            window.location.href = '/login.html';
            return;
        }

        // 加载用户信息
        const user = JSON.parse(localStorage.getItem('user'));
        if (user) {
            $('#userInfo').html(`欢迎，${user.username} <span class="badge badge-primary">${user.role}</span>`);
        }

        // 加载图书数据
        loadBooks();

        // 绑定事件处理函数
        bindEvents();
    });

    // 绑定所有事件处理函数
    function bindEvents() {
        // 搜索按钮点击事件
        $('#searchBtn').click(function() {
            const criteria = {
                title: $('#searchTitle').val().trim(),
                author: $('#searchAuthor').val().trim(),
                isbn: $('#searchIsbn').val().trim()
            };
            loadBooks(criteria);
        });

        // 重置按钮点击事件
        $('#resetBtn').click(function() {
            $('#searchTitle').val('');
            $('#searchAuthor').val('');
            $('#searchIsbn').val('');
            loadBooks();
        });

        // 添加图书按钮点击事件
        $('#addBookBtn').click(function() {
            $('#modalTitle').text('添加新图书');
            $('#bookForm')[0].reset();
            $('#bookId').val('');
            $('#bookModal').css('display', 'flex');
        });

        // 关闭模态框按钮点击事件
        $('#closeModal, #cancelBtn').click(function() {
            $('#bookModal').css('display', 'none');
        });

        // 关闭消息模态框
        $('#closeMessageModal, #confirmMessageBtn').click(function() {
            $('#messageModal').css('display', 'none');
        });

        // 登出按钮点击事件
        $('#logoutLink').click(function(e) {
            e.preventDefault();
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('token');
                localStorage.removeItem('user');
                window.location.href = '/login.html';
            }
        });

        // 图书表单提交事件
        $('#bookForm').submit(function(e) {
            e.preventDefault();
            saveBook();
        });

        // 点击模态框外部关闭模态框
        $(window).click(function(e) {
            if (e.target === document.getElementById('bookModal')) {
                $('#bookModal').css('display', 'none');
            }
            if (e.target === document.getElementById('messageModal')) {
                $('#messageModal').css('display', 'none');
            }
        });
    }

    // 从API加载图书数据
    function loadBooks(criteria = {}) {
        showLoading(true);
        const token = localStorage.getItem('token');
        let url = '/api/books';

        // 构建查询参数
        if (Object.keys(criteria).length > 0) {
            const params = [];
            Object.entries(criteria).forEach(([key, value]) => {
                if (value) params.push(`${key}=${encodeURIComponent(value)}`);
            });
            if (params.length > 0) {
                url += `?${params.join('&')}`;
            }
        }

        // 发起请求
        $.ajax({
            url: url,
            type: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`
            },
            dataType: 'json',
            success: function(books) {
                renderBooksTable(books);
                showLoading(false);
            },
            error: function(xhr) {
                showLoading(false);
                handleError(xhr);
            }
        });
    }

    // 渲染图书表格
    function renderBooksTable(books) {
        const tableBody = $('#booksTableBody');
        tableBody.empty();

        if (books.length === 0) {
            const emptyRow = $('<tr><td colspan="10" class="text-center">没有找到图书数据</td></tr>');
            tableBody.append(emptyRow);
            return;
        }

        books.forEach(book => {
            const row = $('<tr>');
            row.html(`
                <td>${book.id}</td>
                <td>${book.isbn}</td>
                <td>${book.title}</td>
                <td>${book.author}</td>
                <td>${book.publisher || '-'}</td>
                <td>${book.publicationYear || '-'}</td>
                <td>${book.category || '-'}</td>
                <td>${book.quantity}</td>
                <td>${book.availableQuantity}</td>
                <td>
                    <button class="btn btn-sm btn-primary btn-action edit-btn" data-id="${book.id}">
                        <i class="bi bi-pencil"></i> 编辑
                    </button>
                    <button class="btn btn-sm btn-danger btn-action delete-btn" data-id="${book.id}">
                        <i class="bi bi-trash"></i> 删除
                    </button>
                </td>
            `);
            tableBody.append(row);
        });

        // 绑定编辑和删除按钮事件
        $('.edit-btn').click(function() {
            editBook($(this).data('id'));
        });

        $('.delete-btn').click(function() {
            deleteBook($(this).data('id'));
        });
    }

    // 编辑图书
    function editBook(id) {
        showLoading(true);
        const token = localStorage.getItem('token');

        $.ajax({
            url: `/api/books/${id}`,
            type: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`
            },
            dataType: 'json',
            success: function(book) {
                showLoading(false);
                $('#modalTitle').text('编辑图书');
                $('#bookId').val(book.id);
                $('#isbn').val(book.isbn);
                $('#title').val(book.title);
                $('#author').val(book.author);
                $('#publisher').val(book.publisher || '');
                $('#publicationYear').val(book.publicationYear || '');
                $('#category').val(book.category || '');
                $('#quantity').val(book.quantity);
                $('#availableQuantity').val(book.availableQuantity);
                $('#bookModal').css('display', 'flex');
            },
            error: function(xhr) {
                showLoading(false);
                handleError(xhr);
            }
        });
    }

    // 保存图书（新增或更新）
    function saveBook() {
        showLoading(true);
        const token = localStorage.getItem('token');
        const bookId = $('#bookId').val();
        const isAdd = !bookId;

        const bookData = {
            isbn: $('#isbn').val().trim(),
            title: $('#title').val().trim(),
            author: $('#author').val().trim(),
            publisher: $('#publisher').val().trim(),
            publicationYear: $('#publicationYear').val() ? parseInt($('#publicationYear').val()) : null,
            category: $('#category').val().trim(),
            quantity: parseInt($('#quantity').val()),
            availableQuantity: parseInt($('#availableQuantity').val())
        };

        // 验证可借数量不能超过总数量
        if (bookData.availableQuantity > bookData.quantity) {
            showMessage('错误', '可借数量不能超过总数量', 'error');
            showLoading(false);
            return;
        }

        let url = '/api/books';
        let method = 'POST';

        if (!isAdd) {
            url = `/api/books/${bookId}`;
            method = 'PUT';
        }

        $.ajax({
            url: url,
            type: method,
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
            data: JSON.stringify(bookData),
            success: function() {
                showLoading(false);
                $('#bookModal').css('display', 'none');
                showMessage('成功', isAdd ? '图书添加成功' : '图书更新成功', 'success');
                loadBooks(); // 重新加载图书列表
            },
            error: function(xhr) {
                showLoading(false);
                const errorMsg = xhr.responseText || (isAdd ? '图书添加失败' : '图书更新失败');
                showMessage('错误', errorMsg, 'error');
            }
        });
    }

    // 删除图书
    function deleteBook(id) {
        if (!confirm('确定要删除这本图书吗？此操作不可恢复！')) {
            return;
        }

        showLoading(true);
        const token = localStorage.getItem('token');

        $.ajax({
            url: `/api/books/${id}`,
            type: 'DELETE',
            headers: {
                'Authorization': `Bearer ${token}`
            },
            success: function() {
                showLoading(false);
                showMessage('成功', '图书删除成功', 'success');
                loadBooks(); // 重新加载图书列表
            },
            error: function(xhr) {
                showLoading(false);
                const errorMsg = xhr.responseText || '图书删除失败';
                showMessage('错误', errorMsg, 'error');
            }
        });
    }

    // 显示/隐藏加载提示
    function showLoading(show) {
        $('#loading').css('display', show ? 'block' : 'none');
    }

    // 显示消息提示
    function showMessage(title, content, type) {
        $('#messageTitle').text(title);
        $('#messageContent').text(content);

        // 根据消息类型设置标题样式
        if (type === 'success') {
            $('#messageTitle').removeClass('text-danger').addClass('text-success');
        } else if (type === 'error') {
            $('#messageTitle').removeClass('text-success').addClass('text-danger');
        } else {
            $('#messageTitle').removeClass('text-success text-danger');
        }

        $('#messageModal').css('display', 'flex');
    }

    // 处理错误
    function handleError(xhr) {
        if (xhr.status === 401) {
            // Token过期或无效，需要重新登录
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            showMessage('登录过期', '您的登录已过期，请重新登录', 'error');
            setTimeout(() => {
                window.location.href = '/login.html';
            }, 1500);
        } else {
            const errorMsg = xhr.responseText || '操作失败，请稍后重试';
            showMessage('错误', errorMsg, 'error');
        }
    }
</script>
</body>
</html>
